# -*- coding: utf-8 -*-

import json
import logging
from datetime import datetime
from odoo import http, fields
from odoo.http import request
from odoo.exceptions import ValidationError, AccessError
from .api_base import api_response, verify_api_token, check_department_permission
import io

_logger = logging.getLogger(__name__)


class MaintenanceController(http.Controller):
    """设备维保管理控制器"""

    @http.route('/api/maintenance/list', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    #@api_response
    @verify_api_token
    # @check_api_permission('device:maintenance:list')  # 已注释按钮权限，改用部门权限
    @check_department_permission
    def list_maintenance(self, **kwargs):
        """获取设备维保列表"""
        page = kwargs.get('pageNum', 1)
        size = kwargs.get('pageSize', 10)
        equipment_id = kwargs.get('equipmentId', '')
        equipment_name = kwargs.get('equipmentName', '')
        maintenance_pr = kwargs.get('maintenancePr', '')
        status = kwargs.get('status', '')
        maintenance_type = kwargs.get('maintenanceType', '')
        start_date = kwargs.get('startDate', '')
        end_date = kwargs.get('endDate', '')
        
        domain = []
        if equipment_id:
            domain.append(('equipment_id', '=', int(equipment_id)))
        if equipment_name:
            domain.append(('equipment_name', 'ilike', equipment_name))
        if maintenance_pr:
            domain.append(('maintenance_pr', 'ilike', maintenance_pr))
        if status:
            domain.append(('status', '=', status))
        if maintenance_type:
            domain.append(('maintenance_type', '=', maintenance_type))
        if start_date:
            domain.append(('start_date', '>=', start_date))
        if end_date:
            domain.append(('end_date', '<=', end_date))
        
        # 部门权限过滤
        current_user = getattr(request, 'current_api_user', None)
        if current_user:
            # 检查是否是admin账号，admin账号拥有全部权限
            if hasattr(current_user, 'is_admin') and current_user.is_admin:
                # admin账号可以看到所有维保记录，不添加过滤条件
                pass
            else:
                user_department = current_user.department_id
                if user_department:
                    # 检查用户是否是部门负责人
                    is_department_leader = user_department.leader_id and user_department.leader_id.id == current_user.id
                    
                    if is_department_leader:
                        # 部门负责人：可以看到该部门下的所有设备相关维保
                        equipment_ids = request.env['device.equipment'].sudo().search([
                            ('department_id', '=', user_department.id)
                        ]).ids
                        if equipment_ids:
                            domain.append(('equipment_id', 'in', equipment_ids))
                        else:
                            domain.append(('id', '=', False))
                    else:
                        # 非部门负责人：只能看到设备绑定用户为自己的维保记录
                        equipment_ids = request.env['device.equipment'].sudo().search([
                            ('user_id', '=', current_user.id)
                        ]).ids
                        if equipment_ids:
                            domain.append(('equipment_id', 'in', equipment_ids))
                        else:
                            # 如果没有绑定设备，返回空结果
                            domain.append(('id', '=', False))
                else:
                    # 没有部门信息，返回空结果
                    domain.append(('id', '=', False))
            
        # 计算总数
        total = request.env['device.maintenance'].search_count(domain)
            
        # 获取数据
        offset = (page - 1) * size
        maintenances = request.env['device.maintenance'].search(domain, offset=offset, limit=size, order='start_date desc')
            
        # 构建返回数据
        rows = []
        for maintenance in maintenances:
            rows.append({
                'maintenanceId': maintenance.id,
                'equipmentId': maintenance.equipment_id.id,
                'equipmentName': maintenance.equipment_name,
                'equipmentCode': maintenance.equipment_code,
                'equipmentCategory': maintenance.equipment_category,
                'equipmentModel': maintenance.equipment_model,
                'maintenancePr': maintenance.maintenance_pr or '',
                'maintenancePo': maintenance.maintenance_po or '',
                'contractNumber': maintenance.contract_number or '',
                'contractAmount': maintenance.contract_amount,
                'startDate': maintenance.start_date.strftime('%Y-%m-%d %H:%M:%S') if maintenance.start_date else '',
                'endDate': maintenance.end_date.strftime('%Y-%m-%d %H:%M:%S') if maintenance.end_date else '',
                'status': maintenance.status,
                'maintenanceType': maintenance.maintenance_type,
                'serviceProvider': maintenance.service_provider or '',
                'contactPerson': maintenance.contact_person or '',
                'contactPhone': maintenance.contact_phone or '',
                'createTime': maintenance.create_time.strftime('%Y-%m-%d %H:%M:%S') if maintenance.create_time else '',
                'remark': maintenance.remark or ''
            })
        return {
            'code': 200,
            'msg': '查询成功',
            'data': {
                'total': total,
                'rows': rows
            }
        }


    @http.route('/api/maintenance/info/<int:maintenance_id>', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    #@api_response
    @verify_api_token
    # @check_api_permission('device:maintenance:read')  # 已注释按钮权限，改用部门权限
    @check_department_permission
    def get_maintenance(self, maintenance_id, **kwargs):
        """获取维保详情"""
        maintenance = request.env['device.maintenance'].browse(maintenance_id)
        if not maintenance.exists():
            raise ValidationError('维保记录不存在')
        
        data = {
            'maintenanceId': maintenance.id,
            'equipmentId': maintenance.equipment_id.id,
            'equipmentName': maintenance.equipment_name,
            'equipmentCode': maintenance.equipment_code,
            'equipmentCategory': maintenance.equipment_category,
            'equipmentModel': maintenance.equipment_model,
            'maintenancePr': maintenance.maintenance_pr or '',
            'maintenancePo': maintenance.maintenance_po or '',
            'contractNumber': maintenance.contract_number or '',
            'contractAmount': maintenance.contract_amount,
            'startDate': maintenance.start_date.strftime('%Y-%m-%d %H:%M:%S') if maintenance.start_date else '',
            'endDate': maintenance.end_date.strftime('%Y-%m-%d %H:%M:%S') if maintenance.end_date else '',
            'status': maintenance.status,
            'maintenanceType': maintenance.maintenance_type,
            'serviceProvider': maintenance.service_provider or '',
            'contactPerson': maintenance.contact_person or '',
            'contactPhone': maintenance.contact_phone or '',
            'createTime': maintenance.create_time.strftime('%Y-%m-%d %H:%M:%S') if maintenance.create_time else '',
            'updateTime': maintenance.update_time.strftime('%Y-%m-%d %H:%M:%S') if maintenance.update_time else '',
            'createBy': maintenance.create_by,
            'updateBy': maintenance.update_by,
            'remark': maintenance.remark or ''
        }
        return {
            'code': 200,
            'msg': '查询成功',
            'data': data
        }

    @http.route('/api/maintenance/add', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    #@api_response
    @verify_api_token
    # @check_api_permission('device:maintenance:add')  # 已注释按钮权限，改用部门权限
    @check_department_permission
    def add_maintenance(self, **kwargs):
        """新增维保记录"""
        equipment_id = kwargs.get('equipmentId')
        maintenance_pr = kwargs.get('maintenancePr', '')
        maintenance_po = kwargs.get('maintenancePo', '')
        contract_number = kwargs.get('contractNumber', '')
        contract_amount = kwargs.get('contractAmount', 0.0)
        start_date = kwargs.get('startDate')
        end_date = kwargs.get('endDate')
        status = kwargs.get('status', 'planned')
        maintenance_type = kwargs.get('maintenanceType', 'routine')
        service_provider = kwargs.get('serviceProvider', '')
        contact_person = kwargs.get('contactPerson', '')
        contact_phone = kwargs.get('contactPhone', '')
        remark = kwargs.get('remark', '')
        
        if not equipment_id or not start_date or not end_date:
            raise ValidationError('设备、开始时间、结束时间为必填项')
        
        vals = {
            'equipment_id': int(equipment_id),
            'maintenance_pr': maintenance_pr,
            'maintenance_po': maintenance_po,
            'contract_number': contract_number,
            'contract_amount': float(contract_amount),
            'start_date': datetime.strptime(start_date, '%Y-%m-%d %H:%M:%S'),
            'end_date': datetime.strptime(end_date, '%Y-%m-%d %H:%M:%S'),
            'status': status,
            'maintenance_type': maintenance_type,
            'service_provider': service_provider,
            'contact_person': contact_person,
            'contact_phone': contact_phone,
            'remark': remark
        }
        
        maintenance = request.env['device.maintenance'].create(vals)
        return {
            'code': 200,
            'msg': '查询成功',
            'data': {'maintenanceId': maintenance.id}
        }

    @http.route('/api/maintenance/edit', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    #@api_response
    @verify_api_token
    # @check_api_permission('device:maintenance:edit')  # 已注释按钮权限，改用部门权限
    @check_department_permission
    def edit_maintenance(self, **kwargs):
        """修改维保记录"""
        maintenance_id = kwargs.get('maintenanceId')
        if not maintenance_id:
            raise ValidationError('维保记录ID不能为空')
        
        maintenance = request.env['device.maintenance'].browse(int(maintenance_id))
        if not maintenance.exists():
            raise ValidationError('维保记录不存在')
        
        vals = {}
        if 'equipmentId' in kwargs:
            vals['equipment_id'] = int(kwargs['equipmentId'])
        if 'maintenancePr' in kwargs:
            vals['maintenance_pr'] = kwargs['maintenancePr']
        if 'maintenancePo' in kwargs:
            vals['maintenance_po'] = kwargs['maintenancePo']
        if 'contractNumber' in kwargs:
            vals['contract_number'] = kwargs['contractNumber']
        if 'contractAmount' in kwargs:
            vals['contract_amount'] = float(kwargs['contractAmount'])
        if 'startDate' in kwargs:
            vals['start_date'] = datetime.strptime(kwargs['startDate'], '%Y-%m-%d %H:%M:%S')
        if 'endDate' in kwargs:
            vals['end_date'] = datetime.strptime(kwargs['endDate'], '%Y-%m-%d %H:%M:%S')
        if 'status' in kwargs:
            vals['status'] = kwargs['status']
        if 'maintenanceType' in kwargs:
            vals['maintenance_type'] = kwargs['maintenanceType']
        if 'serviceProvider' in kwargs:
            vals['service_provider'] = kwargs['serviceProvider']
        if 'contactPerson' in kwargs:
            vals['contact_person'] = kwargs['contactPerson']
        if 'contactPhone' in kwargs:
            vals['contact_phone'] = kwargs['contactPhone']
        if 'remark' in kwargs:
            vals['remark'] = kwargs['remark']
        
        maintenance.write(vals)

        return {
            'code': 200,
            'msg': '成功'
        }

    @http.route('/api/maintenance/delete', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    #@api_response
    @verify_api_token
    # @check_api_permission('device:maintenance:delete')  # 已注释按钮权限，改用部门权限
    @check_department_permission
    def delete_maintenance(self, **kwargs):
        """删除维保记录"""
        maintenance_ids = kwargs.get('maintenanceIds', [])
        if not maintenance_ids:
            raise ValidationError('请选择要删除的维保记录')
        
        maintenances = request.env['device.maintenance'].browse(maintenance_ids)
        maintenances.unlink()

        return {
            'code': 200,
            'msg': '成功',
        }

    @http.route('/api/maintenance/export', type='http', auth='none', methods=['GET'], csrf=False, cors='*')
    @verify_api_token
    # @check_api_permission('device:maintenance:export')  # 已注释按钮权限，改用部门权限
    @check_department_permission
    def export_maintenance(self, **kwargs):
        """导出维保信息"""
        # 获取查询条件
        equipment_id = kwargs.get('equipmentId', '')
        equipment_name = kwargs.get('equipmentName', '')
        status = kwargs.get('status', '')
        
        domain = []
        if equipment_id:
            domain.append(('equipment_id', '=', int(equipment_id)))
        if equipment_name:
            domain.append(('equipment_name', 'ilike', equipment_name))
        if status:
            domain.append(('status', '=', status))
        
        maintenances = request.env['device.maintenance'].search(domain)
        
        # 构建Excel数据
        import xlsxwriter
        output = io.BytesIO()
        workbook = xlsxwriter.Workbook(output)
        worksheet = workbook.add_worksheet('设备维保信息')
        
        # 设置标题
        headers = [
            '设备编号', '设备名称', '设备类别', '设备型号', '维保PR', '维保PO',
            '合同编号', '合同金额', '开始时间', '结束时间', '维保状态', '维保类型',
            '服务商', '联系人', '联系电话', '创建时间', '备注'
        ]
        
        # 写入标题
        for col, header in enumerate(headers):
            worksheet.write(0, col, header)
        
        # 写入数据
        for row, maintenance in enumerate(maintenances, 1):
            status_dict = dict(maintenance._fields['status'].selection)
            type_dict = dict(maintenance._fields['maintenance_type'].selection)
            
            data = [
                maintenance.equipment_code,
                maintenance.equipment_name,
                maintenance.equipment_category,
                maintenance.equipment_model,
                maintenance.maintenance_pr or '',
                maintenance.maintenance_po or '',
                maintenance.contract_number or '',
                maintenance.contract_amount,
                maintenance.start_date.strftime('%Y-%m-%d %H:%M:%S') if maintenance.start_date else '',
                maintenance.end_date.strftime('%Y-%m-%d %H:%M:%S') if maintenance.end_date else '',
                status_dict.get(maintenance.status, maintenance.status),
                type_dict.get(maintenance.maintenance_type, maintenance.maintenance_type),
                maintenance.service_provider or '',
                maintenance.contact_person or '',
                maintenance.contact_phone or '',
                maintenance.create_time.strftime('%Y-%m-%d %H:%M:%S') if maintenance.create_time else '',
                maintenance.remark or ''
            ]
            
            for col, value in enumerate(data):
                worksheet.write(row, col, value)
        
        workbook.close()
        output.seek(0)
        
        # 生成文件名
        filename = f"设备维保信息_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
        
        response = request.make_response(
            output.getvalue(),
            headers=[
                ('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'),
                ('Content-Disposition', f'attachment; filename="{filename}"')
            ]
        )
        output.close()
        return response
